<template>
  <div>
    <hot-table
      ref="hotTable"
      :data="templateData"
      :settings="hotSettings"
      class="margin-top text-sm"
    ></hot-table>
    <div v-loading.fullscreen.lock="fullscreenLoading"></div>
  </div>
</template>

<script>
import { parseTime, getFindKey } from "@/utils";
import { clone } from "@/utils/clone";
import { HotTable } from "@handsontable/vue";
import Handsontable from "handsontable";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import "handsontable/languages/zh-CN";
import "handsontable/dist/handsontable.full.css";
import globalData from "@/utils/config";

// import { log } from "console";
export default {
  components: {
    HotTable
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    templateName: {
      validator: function(value) {
        // 这个值必须匹配下列字符串中的一个
        return ["Receivable", "Payable"].indexOf(value) !== -1;
      }
    },
    templateType: {
      type: String,
      default: "receivable"
    },
    templateOptUser: {
      type: String,
      default: ""
    },

    templateData: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    oldData: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    receveToPay: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    payToReceve: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    templateDelReceveIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateDelPayIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateOptions: {
      type: Object,
      default: function(params) {
        return {};
      }
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      autoHeight: "auto",
      fullscreenLoading: false,
      rowIndex: 0,
      selectHead: [],
      headerList: [
        `序号`,
        "<span style='color:red;'>公司</span>",
        "<span style='color:red;'>费用名称</span>",
        "<span style='color:red;'>数量</span>",
        "<span style='color:red;'>单价</span>",
        "<span style='color:red;'>币种</span>",
        "总额",
        "余额",
        "<span style='color:red;'>账单类型</span>",
        "录入人",
        "修改人",
        "备注",
        "费用日期",
        "操作"
      ],
      columns1: [
        {
          data: "ynChoice",
          width: 40,
          type: "checkbox",
          checkedTemplate: 1,
          uncheckedTemplate: 0
        },
        {
          data: "serCusId", // 公司
          // width: 200,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.companyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "costName", // 费用名称
          // width: 80,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.configPayNameOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },

        {
          data: "count", //数量
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "unitPrice", //单价
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            console.log("val :>> ", val);
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
              // c;
            }

            val = val.slice(0, val.indexOf("."));
            console.log("val :>> ", val);
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.currencyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "totalCost", //总额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "remain", // 余额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "billType", //账单类型
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.options
        },

        {
          data: "inputUser", // 录入人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "lastOperator", //修改人
          readOnly: true,
          // width: 80,
          type: "text"
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        },

        {
          data: "accountDate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        // {
        //   data: "cdate",
        //   width: 100,
        //   type: "date",
        //   dateFormat: "YYYY-MM-DD"
        // },
        {
          readOnly: true,
          // width: 100,
          renderer: this.coverRenderer
        }
      ],
      //应付
      columns2: [
        {
          data: " ",
          width: 40,
          type: "checkbox"
        },
        {
          data: "serCusId", // 公司
          // width: 200,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.serviceOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "costName", // 费用名称
          // width: 80,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.configPayNameOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },

        {
          data: "count", //数量
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "unitPrice", //单价
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            console.log("val :>> ", val);
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }

            val = val.slice(0, val.indexOf("."));
            console.log("val :>> ", val);
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.currencyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "totalCost", //总额remain totalCost
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "remain", // 余额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "billType", //账单类型
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.options
        },
        // {
        //   data: "isAllocated", // 是否分配
        //   width: 80,
        //   readOnly: true,
        //   type: "text"
        // },
        {
          data: "inputUser", // 录入人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "lastOperator", //修改人
          readOnly: true,
          // width: 80,
          type: "text"
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        },

        {
          data: "accountDate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        // {
        //   data: "cdate",
        //   width: 100,
        //   type: "date",
        //   dateFormat: "YYYY-MM-DD"
        // },
        {
          readOnly: true,
          // width: 100,
          renderer: this.coverRenderer
        }
      ],

      changeList: [],
      props: [
        "serCusId",
        "costName",
        "count",
        "unitPrice",
        "currency",
        "billType"
      ],
      delId: ""
    };
  },
  computed: {
    hotSettings() {
      return {
        currentRowClassName: "currentRow", // 为选中行添加类名，可以更改样式
        currentColClassName: "currentCol", // 为选中列添加类名
        // rowHeaders: true, // 行表头
        // headerTooltips: true, // 鼠标划过头部时的提示文字
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: this.headerList,
        width: "100%",
        height: 500,
        // height: this.autoHeight,
        columns:
          this.templateType === "receivable" ? this.columns1 : this.columns2,
        tableClassName: [`table-${this.templateType}`],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        cells: this.rowReadonly,
        beforeRemoveRow: async (index, amount, physicalRows, source) => {
          for (const i of physicalRows) {
            if (
              this.templateData[i].totalCost !== this.templateData[i].remain
            ) {
              this.$message.error("余额不等于总额，无法删除");
              return false;
            }
          }

          if (
            (this.templateType === "receivable" &&
              !this.verifyShow.deleteRece) ||
            (this.templateType === "payable" && !this.verifyShow.deletePay)
          ) {
            return false;
          }

          if (amount > 1) {
            this.$message.error("当前不支持删除多行");
            return false;
          }
          this.delId = this.templateData[physicalRows[0]].id
            ? this.templateData[physicalRows[0]].id
            : "";

          if (this.delId) {
            const flag = await this.saveDel({ id: this.delId });
            return flag;
          }

          if (this.templateData.length === 1) {
            this.templateData.push({});
          }
        },
        beforeChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          console.log("changes: ", changes); // row, prop, oldVal, newVal
          console.log("source: ", source); // op
          if (source && "edit" == source) {
            const [row, prop, oldValue, newValue] = changes[0];
            // 判断余额 是否等于总额
            if (
              prop !== "ynChoice" &&
              this.templateData[row].remain !== this.templateData[row].totalCost
            ) {
              console.log("不可编辑 :>> ");
              this.$notify.error({
                position: "bottom-right",
                message: "更改失败，费用已销账"
              });
              changes.length = 0;
              return;
            }
            if (prop) {
              if (prop == "count" && oldValue != newValue) {
                // 修改数量
                if (this.templateData[row].unitPrice < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }

                this.changeCount(row, newValue);
              } else if (prop == "unitPrice" && oldValue != newValue) {
                // 修改单价
                if (this.templateData[row].count < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }
                this.changeUnitPrice(row, newValue);
              }
            }
          }
        },

        // afterDocumentKeyDown: Event => {
        //   this.checkRowInChange();
        // },

        afterChange: async (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          // console.log("changes :>> ", changes);
          // 保存成功数据
          this.setTdClass();

          if (!changes) return;
          const [row, prop, oldValue, newValue] = changes[0];
          console.log("prop :>> ", prop);

          // TODO

          // this.templateData[row]
          if (
            oldValue != newValue &&
            this.templateData[row].id &&
            prop !== "ynChoice"
          ) {
            this.templateData[row].lastOperator = this.templateOptUser;
          }

          if (prop === "ynChoice" && this.templateData[row].id) {
            this.updateAbroadReceivable(newValue, this.templateData[row].id);
          }

          if (oldValue != newValue && prop !== "ynChoice") {
            const oldData = JSON.parse(
              sessionStorage.getItem(this.templateType)
            );

            const list =
              this.templateType === "receivable"
                ? this.columns1
                : this.columns2;
            const col = list.findIndex(x => x.data === prop);

            if (
              (oldData[row] &&
                oldData[row][prop] !== this.templateData[row][prop]) ||
              !oldData[row]
            ) {
              await this.removeTdClass(row);
              const target = this.changeList.findIndex(
                x => x.row === row && x.col === 0
              );
              if (target > -1) {
                this.changeList.splice(target, 1);
              }

              this.changeList.push({
                row: row,
                col: 0,
                status: "change"
              });

              this.changeList.push({
                row: row,
                col: col,
                status: "change"
              });

              // console.log("修改必填数据 :>> ", this.changeList);

              this.setTdClass();
            }

            // 存在旧值，并且修改后的值 等于旧值
            if (
              oldData[row] &&
              oldData[row][prop] === this.templateData[row][prop]
            ) {
              await this.removeTdClass(row);
              this.templateData[row].lastOperator = this.templateOptUser;
              // 剔除坐标
              this.changeList.splice(
                this.changeList.indexOf(row + "," + col),
                1
              );
              for (const i in this.changeList) {
                if (this.changeList[i].row === row && this.changeList[i].col) {
                  this.changeList.splice(i, 1);
                }
              }
              this.setTdClass();
            }

            // sessionStorage.setItem("changeList", this.changeList);
          }
        },
        /**
         * [一个或多个cell被选中后触发(每选中一个触发一次)]
         * @param  {[number]} row              [开始cell的行索引]
         * @param  {[number]} column           [开始cell的列索引]
         * @param  {[number]} row2             [结束cell的行索引]
         * @param  {[number]} column2          [结束cell的列索引]
         * @param  {[object]} preventScrolling [Object with value property where its value change will be observed]
         * @param  {[number]} selectionLayerLevel [被选中的层级]
         */
        afterSelection: (
          row,
          prop,
          row2,
          prop2,
          preventScrolling,
          selectionLayerLevel
        ) => {
          setTimeout(async () => {
            if (row !== this.rowIndex) {
              await this.checkRowInChange();
            }
            this.rowIndex = row;
          });
        },
        /**
         * [当前单元格不被选中后触发]
         */
        afterDeselect: () => {
          console.log("当前单元格不被选中后触发 :>> ", this.rowIndex);
          setTimeout(() => {
            this.checkRowInChange();
          });
        },
        /**
         * [一行或者多行移除后触发]
         * @param  {[number]} index        [起始行的可视索引]
         * @param  {[number]} amount       [删除行的数量]
         * @param  {[array]}  physicalRows [被删除行的数据组成的数组]
         * @param  {[string]} source       [触发的源]
         */
        afterRemoveRow: (index, amount, physicalRows, source) => {}
      };
    }
  },
  watch: {
    templateData: {
      handler(val) {
        var length = val.length;
        if (length < 10) {
          this.autoHeight = "350px";
        } else {
          this.autoHeight = "auto";
        }
      },
      immediate: true,
      deep: true
    },
    templateOptions: {
      handler(val) {
        // console.log("val :>> ", val);
      },
      immediate: true,
      deep: true
    },
    oldData: {
      handler(val) {
        sessionStorage.setItem(this.templateType, JSON.stringify(this.oldData));
      }
    }
  },
  created() {
    this.selectHead = [`<input type='checkbox' name=[]' ></input>`];
  },
  mounted() {},

  methods: {
    updateAbroadReceivable(type, id) {
      ajax("updateAbroadReceivable", {
        ynChoice: type,
        id: id
      }).then(res => {
        console.log("res :>> ", res);
      });
    },
    async setTdClass() {
      setTimeout(() => {
        console.log("this.changeList :>> ", this.changeList);
        for (const i of this.changeList) {
          const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
            .children[0].children[0].children[2].children[i.row].children[
            i.col
          ];
          switch (i.status) {
            case "change":
              td.classList.add("bg-yellow");
              break;
            case "success":
              td.classList.add("bg-green");
              break;
            case "error":
              td.classList.add("bg-red");
              break;
          }
        }
      });
    },
    removeTdClass(row) {
      const elements = document
        .getElementsByClassName(`table-${this.templateType}`)[0]
        .querySelectorAll("td");

      Array.prototype.forEach.call(elements, function(element) {
        element.classList.remove("bg-yellow", "bg-green", "bg-red");
      });
    },
    async checkRowInChange() {
      const a = this.changeList.filter(i => i.row === this.rowIndex);
      if (a.length > 0) {
        console.log("执行保存 :>> ");
        // 执行保存
        await this.saveRowInfo(this.rowIndex);
      }
    },

    async saveRowInfo(row, type) {
      const index = clone(row);
      console.log("index :>> ", index);
      console.log("this.templateData[index] :>> ", this.templateData);

      for (const j of this.props) {
        if (!this.templateData[index][j]) return;
      }
      if (
        this.templateData[index].totalCost &&
        parseFloat(this.templateData[index].totalCost).toFixed(2) !==
          (
            (this.templateData[index].count *
              1000 *
              (this.templateData[index].unitPrice * 1000)) /
            1000000
          ).toFixed(2)
      ) {
        this.$message.error("总额不等于单价*数量，请检查");
        return false;
      }
      let td = null;
      if (!type) {
        const length =
          this.templateType === "receivable"
            ? this.columns1.length - 1
            : this.columns2.length - 1;

        td = this.$refs.hotTable.$el.children[0].children[0].children[0].children[0].children[0].children[2].children[
          row
        ].children[length].getElementsByClassName("el-icon-loading")[0];
        console.log("td :>> ", td);
        td.style = "display:black";
      }

      // saveAbroadReceivable 应收
      // saveAbroadPayment 应付
      const apiName =
        this.templateType === "receivable"
          ? "saveAbroadReceivable"
          : "saveAbroadPayment";

      const d = clone(this.templateData[index]);
      for (const j in d) {
        if (j === "serCusId") {
          const map =
            this.templateType === "receivable"
              ? this.templateOptions.customerMap
              : this.templateOptions.serveCompanyMap;

          d.serCusId = getFindKey(d.serCusId, map);
        } else if (j === "costName") {
          d.costName = getFindKey(d.costName, this.templateOptions.payNameMap);
        } else if (j === "inputUser") {
          d.inputUser = getFindKey(d.inputUser, this.templateOptions.userMap);
        } else if (j === "lastOperator") {
          d.lastOperator = getFindKey(
            d.lastOperator,
            this.templateOptions.userMap
          );
        } else if (j === "billType") {
          d.billType = d.billType === "起" ? 0 : 1;
        }
      }

      d.costOrigini = 1;
      d.waybillId = parseInt(this.$route.query.pid);
      d.waybillNo = this.Constatvariable.waybillNo;
      d.cuser = parseInt(this.$store.state.auth.user.id);
      console.log(apiName, " :>> ", this.Constatvariable.waybillNo);
      console.log(apiName, " :>> ", d);

      const { code, message } = await ajax(apiName, d);
      const list = clone(this.changeList);
      if (code === 200) {
        await this.removeTdClass(row);
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].row == row) {
            list.splice(i, 1);
          }
        }
        list.push({
          row: index,
          col: 0,
          status: "success"
        });
        this.$message.success("保存成功!");
        this.$emit("getInfo");
      } else {
        list.push({
          row: index,
          col: 0,
          status: "error"
        });
        this.$message.error(message ? message : "保存失败!");
      }
      if (!type && td) {
        td.style = "display:none";
      }

      this.changeList = list;
      this.setTdClass();
    },
    //行只读
    rowReadonly(row, col, prop) {
      var cellProperties = {};
      if (this.templateType === "receivable" && !this.verifyShow.editRece) {
        cellProperties.readOnly = true;
      }
      if (this.templateType === "payable" && !this.verifyShow.editPay) {
        cellProperties.readOnly = true;
      }
      return cellProperties;
    },
    changePayName(index, val) {
      var payType = this.templateOptions.payNameTypeMap[val];
      this.$set(this.templateData[index], "costNameType", payType);
    },
    changeCount(index, val) {
      const target = this.templateData[index];
      const totalCost = (target.unitPrice * 100 * val) / 100;

      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },
    changeUnitPrice(index, val) {
      const target = this.templateData[index];
      const totalCost = (val * 100 * target.count) / 100;
      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },

    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = ``; // 清空单元格子集

      let btnCopy = document.createElement("i");
      let btn2 = document.createElement("i");
      btnCopy.onclick = params => {
        this.onCopy(row);
      };
      btnCopy.setAttribute(
        "class",
        "el-icon-circle-plus-outline margin-right-sm text-green"
      );

      if (
        (this.templateType === "receivable" && this.verifyShow.createRece) ||
        (this.templateType === "payable" && this.verifyShow.createPay)
      ) {
        td.appendChild(btnCopy); //添加按钮到单元格
      }

      let btnDel = document.createElement("i");

      btnDel.setAttribute(
        "class",
        "el-icon-remove-outline margin-right-sm text-red"
      );
      btnDel.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
      btnDel.onclick = params => {
        // console.log("this :>> ", this);
        this.onDel(row);
      };
      if (
        (this.templateType === "receivable" && this.verifyShow.deleteRece) ||
        (this.templateType === "payable" && this.verifyShow.deletePay)
      ) {
        td.appendChild(btnDel); //添加按钮到单元格
      }

      const icon = document.createElement("i");
      icon.setAttribute("class", "el-icon-loading margin-left-sm text-blue ");
      icon.style = "display:none";
      td.appendChild(icon);
      return td;
    },
    removeChangList(data, row) {
      let arr = [];
      for (const i of data) {
        if (i.row > row) {
          i.row -= 1;
          arr.push({
            row: i.row - 1,
            col: i.col,
            status: i.status
          });
        } else if (i.row < row) {
          arr.push(i);
        }
      }

      console.log("arr :>> ", arr);

      this.changeList = arr;
      this.setTdClass();
    },
    async onDel(row) {
      if (this.templateData.length > 0) {
        const tData = clone(this.templateData);
        const data = this.templateData[row];
        if (this.templateType === "receivable") {
          if (data && null != data["id"] && "" != data["id"]) {
            this.fullscreenLoading = true;
            //搞一下测试
            var param = {};

            param["id"] = data["id"];
            await this.saveDel(param, "receivable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台

            this.templateData.splice(row, 1);
            this.removeChangList(tData, row);
            const data = clone(this.templateData);
            sessionStorage.setItem(this.templateType, JSON.stringify(data));
          }
        } else if (this.templateType === "payable") {
          if (data && null != data["id"] && "" != data["id"]) {
            this.fullscreenLoading = true;
            var param = {};
            param["id"] = data["id"];
            await this.saveDel(param, "payable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台
            this.templateData.splice(row, 1);
            this.removeChangList(tData, row);
            const data = clone(this.templateData);
            sessionStorage.setItem(this.templateType, JSON.stringify(data));
          }
        }
      }
    },
    saveDel(param, type, row) {
      return new Promise((resolve, reject) => {
        const apiName =
          type === "receivable"
            ? "deleteAbroadReceivable"
            : "deleteAbroadPayment";
        ajax(apiName, param)
          .then(res => {
            this.fullscreenLoading = false;
            if (res.code == 200) {
              // this.templateDelReceveIds.push(delId);

              this.$message.success("删除成功!");
              if (row) {
                this.templateData.splice(row, 1);
                this.removeChangList(tData, row);
              }

              const data = clone(this.templateData);
              sessionStorage.setItem(this.templateType, JSON.stringify(data));

              this.delId = "";
              resolve(true);
            } else {
              resolve(false);
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,删除失败!");
              }
            }
          })
          .catch(error => {
            console.log(error);
            reject();
          });
      });
    },
    onCopy(row) {
      // if (this.templateName === "Receivable") {
      const data = this.templateData[row];
      this.templateData.splice(row + 1, 0, {
        serCusId: data.serCusId,
        costName: data.costName,
        costNameType: data.costNameType,
        configPayTypec: "",
        responsibleId: data.responsibleId,
        inputUser: this.templateOptUser,
        lastOperator: null,
        unitPrice: data.unitPrice,
        count: data.count,
        currency: data.currency,
        totalCost: data.totalCost,
        remain: data.totalCost,
        billType: data.billType,
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      });
      // }
      this.saveRowInfo(row + 1, "add");
    },
    copyToPayable(row) {
      this.$confirm("确认复制到应付？")
        .then(_ => {
          console.log(this.templateData[row]);
          var target = clone(this.templateData[row]);
          console.log("------------------------");
          if (this.checkRule(target)) {
            this.fullscreenLoading = true;
            var list = [];
            target["isSync"] = 1;
            list.push(target);
            console.log("当前的复制的应付数据");
            ajax("saveWaybillPayablesBaseInfo", list).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code == 200) {
                  // target.lastOperator = "";
                  // target.inputUser = this.templateOptUser;
                  // target.accountDate = target.cdate = parseTime(
                  //   new Date().toLocaleDateString(),
                  //   "{y}-{m}-{d}"
                  // );
                  target.id = res.data;
                  this.receveToPay.push(target);
                  target["isSync"] = 0;
                  // TODO 保存操作 更新数据
                } else {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,同步失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }
        })
        .catch(_ => {});
    },

    saveToPayable(row) {
      this.$confirm("确认保存应付？")
        .then(_ => {
          console.log(this.templateData[row]);
          var target = this.templateData[row];
          target["waybillId"] = this.$route.query.waybillId;
          console.log("------------------------");
          if (this.checkRule(target)) {
            this.fullscreenLoading = true;
            var list = [];
            list.push(target);
            ajax("saveWaybillPayablesBaseInfo", list).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code == 200) {
                  target.lastOperator = "";
                  target.inputUser = this.templateOptUser;
                  target.accountDate = target.cdate = parseTime(
                    new Date().toLocaleDateString(),
                    "{y}-{m}-{d}"
                  );
                  if (target.id == null || target.id == "") {
                    target.id = res.data;
                  }
                } else {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,保存失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }
        })
        .catch(_ => {});
    },

    saveToReceivable(row) {
      this.$confirm("确认保存应收？")
        .then(_ => {
          var target = this.templateData[row];
          target["waybillId"] = this.$route.query.waybillId;
          if (this.checkRule(target)) {
            this.fullscreenLoading = true;
            var list = [];
            list.push(target);
            ajax("saveWaybillReceiveBaseInfo", list).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code == 200) {
                  target.lastOperator = "";
                  target.inputUser = this.templateOptUser;
                  target.accountDate = target.cdate = parseTime(
                    new Date().toLocaleDateString(),
                    "{y}-{m}-{d}"
                  );
                  if (target.id == null || target.id == "") {
                    target.id = res.data;
                  }
                } else {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,保存失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }
        })
        .catch(_ => {});
    },

    copyToReceivable(row) {
      this.$confirm("确认复制到应收？")
        .then(_ => {
          var target = clone(this.templateData[row]);

          if (this.checkRule(target)) {
            this.fullscreenLoading = true;
            var list = [];
            target["isSync"] = 1;
            list.push(target);
            console.log("当前的复制的应付数据");
            ajax("saveWaybillReceiveBaseInfo", list).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code == 200) {
                  target.lastOperator = "";
                  target.inputUser = this.templateOptUser;
                  target.accountDate = target.cdate = parseTime(
                    new Date().toLocaleDateString(),
                    "{y}-{m}-{d}"
                  );
                  target.id = res.data;
                  target["isSync"] = 0;
                  // TODO 公司名等于当前客户
                  this.payToReceve.push(target);
                  // TODO 保存操作 更新数据
                } else {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,同步失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }
        })
        .catch(_ => {});
    },
    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        this.$message.error("请填写责任人");
        return false;
      } else if (i.count !== 0 && !i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (i.unitPrice !== 0 && !i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      } else if (
        i.totalCost &&
        parseFloat(i.totalCost).toFixed(2) !==
          ((i.count * 1000 * (i.unitPrice * 1000)) / 1000000).toFixed(2)
      ) {
        this.$message.error("总额不等于单价*数量，请检查");
        return false;
      }

      return true;
    }
  }
};
</script>

<style></style>
